package com.jadows.tdog.configuration;

import com.jadows.tdog.properties.ChatServerProperties;
import com.jadows.tdog.server.ChatServer;
import com.jadows.tdog.server.ChatServerOptionHandler;
import com.jadows.tdog.server.listener.ChannelEventListener;
import com.jadows.tdog.server.listener.impl.ChatChannelEventListenerImpl;
import com.jadows.tdog.server.option.ChatServerOption;
import com.jadows.tdog.state.OnlineUserRegister;
import com.jadows.tdog.template.DefaultChatServerHandlerTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@EnableConfigurationProperties({ChatServerProperties.class})
@ConditionalOnClass({ChatServer.class})
public class ChatAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(ChatServerOptionHandler.class)
    public ChatServerOptionHandler chatServerOptionHandler() {
        return new DefaultChatServerHandlerTemplate();
    }

    @Bean
    @ConditionalOnMissingBean(ChannelEventListener.class)
    public ChannelEventListener channelEventListener(ChatServerProperties properties,
                                                     OnlineUserRegister onlineUserRegister) {
        return new ChatChannelEventListenerImpl(properties, onlineUserRegister);
    }


    @Bean(initMethod = "start", destroyMethod = "shutdown")
    @ConditionalOnMissingBean(ChatServer.class)
    public ChatServer chatServer(ChatServerOptionHandler chatServerOptionHandler, ChannelEventListener channelEventListener) {
        ChatServerOption option = chatServerOptionHandler.getOption();
        option.listener(channelEventListener);
        return ChatServer.newInstance(option);
    }

}
